import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';

const getOption = (titleName) => ({
  tooltip: {
    trigger: 'item',
  },
  title: {
    text: titleName,
    right: 'center',
    bottom: '0',
    textStyle: {
      color: '#000',
      fontSize: '14px',
      fontWeight: 500,
      fontFamily: 'PingFangSC-Medium',
    },
  },
  legend: {
    show: false,
  },
  series: [
    {
      type: 'pie',
      radius: ['35%', '55%'],
      avoidLabelOverlap: false,
      itemStyle: {
        color(params) {
          // 自定义颜色数组
          const colorList = ['#4191F6', '#80D2AC', '#F0C26D', '#E77D98', '#7A7AE5'];
          return colorList[params.dataIndex];
        },
      },
      label: {
        position: 'outer',
        normal: {
          show: true,
          position: 'outer',
          formatter(params) {
            return `${params.name}\n${params.value}\n{percent|${params.percent}%}`;
          },
          rich: {
            percent: {
              color: '#999',
              fontSize: 10,
            },
          },
        },
      },
      emphasis: {
        label: {},
      },
      labelLine: {
        show: true,
        length: 5, // 调整标签线长度
        length2: 5, // 调整标签线长度
      },
      data: [
        { value: 1233, name: '未执行' },
        { value: 759, name: '当期执行' },
      ],
    },
  ],
});

export const EchartsPie = (props) => {
  const chartRef = useRef(null);

  useEffect(() => {
    const chartDom = chartRef.current;
    const myChart = echarts.init(chartDom);
    myChart.clear();
    const option = getOption(props.name);
    myChart.setOption(option);

    return () => {
      myChart.dispose(); // 在组件卸载时清理echarts实例
    };
  }, [props.name, props.width]);

  return (
    <div style={{ width: props.width }}>
      <div ref={chartRef} style={{ width: '100%', height: '180px', paddingBottom: '10px' }} />
    </div>
  );
};
